<?php

namespace app\api\controller;

use app\admin\model\News;
use app\api\BaseController;
use app\api\middleware\Auth;
use app\command\Mqtt;
use app\common\controller\WeChat;
use app\common\controller\WxPay;
use app\common\service\ElasticsearchService;
use app\common\service\MqttNewService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;
use think\facade\Cache;
use think\Exception;

class Main extends BaseController
{
    protected $middleware = [
        Auth::class => ['except' => ['queryCompanyList', 'ceshi', 'kefu', 'newsDetail', 'svipNewsFile', 'news', 'svipnews', 'uploadImg', 'shai', 'index', 'uploadVideo', 'cityList']]

    ];

    private function postJson($url, $json)
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'token:e9bd5dc569b84672af7bb2310f2f2cc7'],
            CURLOPT_POSTFIELDS     => $json,
            CURLOPT_TIMEOUT        => 10
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    public function queryCompanyList()
    {

        $pageSize = 20;
        $redis    = new \Redis();
        $redis->connect('127.0.0.1', 6379); // 根据你实际配置修改

        $key  = 'company:page';
        $page = $redis->get($key);

        if (!$page) {
            $page = 1;
        }

// 自增并写回
        $redis->set($key, $page + 1);

        $postData = json_encode([
                                    'pageNum'            => $page,
                                    'pageSize'           => $pageSize,
                                    'timestamp'          => 0,
                                    'keyword'            => '',
                                    'cityCode'           => '',
                                    'collectionStatus'   => '',
                                    'emailStatus'        => '',
                                    'estiblishTime'      => '',
                                    'followStatus'       => '',
                                    'industryCode'       => '',
                                    'secondIndustryCode' => '',
                                    'offset'             => 0,
                                    'phoneStatus'        => '',
                                    'provinceCode'       => '',
                                    'regCapital'         => '',
                                    'companyType'        => ''
                                ]);

        $response = $this->postJson('https://www.ruiyanshijie.com/api/search/queryCompanyList', $postData);
        echo $response;
        $data = json_decode($response, true);


        $recordCount = (int)$data['data']['recordCount'];


        $totalPages = (int)ceil($recordCount / $pageSize);

        $companyList = $data['data']['companyInfoDto'] ?? [];
        //var_dump($companyList);
        if (empty($companyList)) {
            return $page;
        }

        $updated = 0;
        foreach ($companyList as $company) {
            $name = $company['companyName'] ?? '';
            if ($name == '') continue;
            echo $name;
            $estiblish = !empty($company['estiblishTime']) ? substr($company['estiblishTime'], 0, 10) : '';
            $phones    = $company['phones'] ?? '';
            $faren     = $company['legalPersonName'] ?? '';

            // 跳过包含 * 的电话字段
            if (strpos($phones, '*') !== false) continue;

            // 构建更新字段数组
            $updateData = [];
            if (!empty($estiblish)) $updateData['riqi'] = $estiblish;
            if (!empty($phones)) $updateData['mobile'] = $phones;
            if (!empty($faren)) $updateData['faren'] = $faren;

            if (!empty($updateData)) {
                if (!empty($estiblish)) {
                    $estiblishYear = (int)substr($estiblish, 0, 4);
                    $currentYear   = (int)date('Y');
                    $age           = $currentYear - $estiblishYear;

                    // 如果当前日期还没到成立周年，则减一年
                    $today = date('Y-m-d');
                    if (date('md', strtotime($today)) < date('md', strtotime($estiblish))) {
                        $age -= 1;
                    }

                    echo "公司成立年限为：{$age} 年";
                }
                $updateData['riqi_year']  = $age;
                $updateData['has_mobile'] = -1;
                var_dump($updateData);
                $result = Db::name('news')
                            ->where('name', $name)
                            ->update($updateData);
                if ($result) $updated++;
            }
        }


        // 渲染页面
        return "当前页数{$page} /总页数{$totalPages} 当前更新了{$updated}条";
    }

    /**
     * 公海信息导出
     */
    public function exportHai()
    {
        $param = get_params();
        $user  = Db::name('user')->where('id', JWT_UID)->find();
        if (empty($user['status'])) {
            return error('您的账号已被禁用，请联系客服');
        }
        $param['ids'] = Db::name('hai')->where(['uid' => JWT_UID, 'type' => 1, 'news_type' => $param['news_type']])->column('news_id');
//        if (empty($param['ids'])) {
//            return error('请选择要导出的线索');
//        }
        $nums = 0;
        $dao  = 0;
        if ($param['news_type'] == 1) {
            if (empty($user['is_vip_one']) && empty($user['is_vip_two'])) {
                return error('请先开通vip');
            }
            if (!empty($user['is_vip_one'])) {
                $user_level = Db::name('user_level')->where('id', 1)->find();
                $nums       += $user_level['read'];
                $dao        += $user_level['dao'];
            }
            if (!empty($user['is_vip_two'])) {
                $user_level = Db::name('user_level')->where('id', 3)->find();
                $nums       += $user_level['read'];
                $dao        += $user_level['dao'];
            }
        } else {
            if (empty($user['is_svip_one']) && empty($user['is_svip_two'])) {
                return error('请先开通svip');
            }
            if (!empty($user['is_svip_one'])) {
                $user_level = Db::name('user_level')->where('id', 2)->find();
                $nums       += $user_level['read'];
                $dao        += $user_level['dao'];
            }
            if (!empty($user['is_svip_two'])) {
                $user_level = Db::name('user_level')->where('id', 4)->find();
                $nums       += $user_level['read'];
                $dao        += $user_level['dao'];
            }
        }
        //今日查看次数
        $start = strtotime(date('Y-m-d'));
        $end   = strtotime(date('Y-m-d 23:59:59'));
        $count = Db::name('news_sel')->where([['create_time', 'between', [$start, $end]], ['uid', '=', JWT_UID]])->count();
        if ($count >= $nums) {
            return error('今日可查看次数不足');
        }
        //今日剩余导出次数
        $after_read = intval($nums - $count);
        $dao_count  = Db::name('news_dao')->where([['create_time', 'between', [$start, $end]], ['uid', '=', JWT_UID]])->count();
        if ($dao_count >= $dao) {
            return error('今日可导出次数不足');
        }
        $after_dao = intval($dao - $dao_count);

        //扣点方式
        if ($param['kou'] == 1) {
            $limit = min($after_dao, 5000); // 限制最多导出5000条
            // $limit = 100000; 

            $where = [['h.news_id', 'in', $param['ids']], ['h.is_read', '=', 1]];
            // 添加筛选条件
            if (!empty($param['is_dao'])) {
                if ($param['is_dao'] == 1) {
                    $where[] = ['h.is_dao', '=', 1];
                } else {
                    $where[] = ['h.is_dao', '=', 0];
                }
            }

            if (!empty($param['is_read'])) {
                if ($param['is_read'] == 1) {
                    $where[] = ['h.is_read', '=', 1];
                } else {
                    $where[] = ['h.is_read', '=', 0];
                }
            }

            $list = Db::name('hai')->alias('h')
                      ->join('news n', 'h.news_id=n.id')
                      ->field('n.*,h.id as hai_id')
                // ->where([['h.id','in',$param['ids']],['h.is_read','=',1]])
                // ->where([['h.news_id','in',$param['ids']], ['h.is_read','=',1]])
                      ->where($where)
                // ->order('id desc')
                      ->limit($limit)
                      ->select()->toArray();
        } else {
            $limit = min($after_read, $after_dao, 5000);
            // $limit = 100000;

            $where = [['h.news_id', 'in', $param['ids']]];
            // 添加筛选条件
            if (!empty($param['is_dao'])) {
                if ($param['is_dao'] == 1) {
                    $where[] = ['h.is_dao', '=', 1];
                } else {
                    $where[] = ['h.is_dao', '=', 0];
                }
            }

            if (!empty($param['is_read'])) {
                if ($param['is_read'] == 1) {
                    $where[] = ['h.is_read', '=', 1];
                } else {
                    $where[] = ['h.is_read', '=', 0];
                }
            }

            $list = Db::name('hai')->alias('h')
                      ->join('news n', 'h.news_id=n.id')
                      ->field('n.*,h.id as hai_id,h.is_read')
                // ->where([['h.id','in',$param['ids']]])
                // ->where([['h.news_id','in',$param['ids']]])
                      ->where($where)
                // ->order('id desc')
                      ->limit($limit)
                      ->select()->toArray();

            if (!empty($list)) {
                $insertAll = [];
                $a         = 0;
                $haiId     = [];
                foreach ($list as &$value) {
                    //是否查看
                    if (empty($value['is_read'])) {
                        $haiId[] = $value['hai_id'];
                    }
                    $is_read = Db::name('news_sel')->where(['uid' => JWT_UID, 'news_id' => $value['id']])->count();
                    if (empty($is_read)) {
                        $insertAll[$a]['uid']         = JWT_UID;
                        $insertAll[$a]['news_id']     = $value['id'];
                        $insertAll[$a]['create_time'] = time();
                        $a++;
                    }
                }
                Db::name('news_sel')->insertAll($insertAll);
                Db::name('hai')->where([['id', 'in', $haiId]])->update(['is_read' => 1]);
            }
        }
        $dao_ids = array_column($list, 'hai_id');
        Db::name('hai')->where([['id', 'in', $dao_ids]])->update(['is_dao' => 1]);
        if (empty($list)) {
            return error('暂无可导出线索');
        }
        // 实例化PHPExcel类
        $objPHPExcel = new Spreadsheet();
        $objActSheet = $objPHPExcel->getActiveSheet();
        if (empty($param['lianxi'])) {
            $lianxi = Db::name('news_field_one')->field('id,name,field_name')->order('id asc')->select()->toArray();
        } else {
            $lianxi = Db::name('news_field_one')->field('id,name,field_name')
                        ->where([['id', 'in', $param['lianxi']]])->order('id asc')->select()->toArray();
        }
        $field_two = Db::name('news_field_two')->field('id,name,field_name')->where([['id', 'in', $param['qita']]])
                       ->order('id asc')->select()->toArray();
        $field_arr = array_merge($field_two, $lianxi);
//        dd($field_arr);
        foreach ($field_arr as $kk => $vv) {
            $objActSheet->setCellValue(zm($kk) . '1', $vv['name']);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(zm($kk))->setWidth(30);
        }
        $add = [];
        for ($i = 0; $i < count($list); $i++) {
            foreach ($field_arr as $k => $v) {
                $objPHPExcel->getActiveSheet()->setCellValue(zm($k) . ($i + 2), $list[$i][$v['field_name']]);
            }
            //写入导出记录表
            $add[$i]['uid']         = JWT_UID;
            $add[$i]['news_id']     = $list[$i]['id'];
            $add[$i]['create_time'] = time();
        }
        Db::name('news_dao')->insertAll($add);
        $filename = 'xiansuo_' . date('YmdHis', time()) . ".xlsx";
        $objPHPExcel->getActiveSheet()->setTitle('企业线索信息');
        $file_path = '/uploads/' . $filename;
        $writer    = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $writer->save('.' . $file_path);
        return success('导出成功', ['path' => $file_path]);
    }

    /**
     * 查看联系方式
     */
    public function selNews()
    {
        $param = get_params();
        $user  = Db::name('user')->where('id', JWT_UID)->find();
        if (empty($user['status'])) {
            return error('您的账号已被禁用，请联系客服');
        }
        $news = Db::name('news')->where('id', $param['id'])->find();
        if (empty($news)) {
            return error('未找到线索信息');
        }
        $nums = 0;
        if ($news['news_file_id'] > 0) {
            if (empty($user['is_svip_one']) && empty($user['is_svip_two'])) {
                return error('请先开通svip');
            }
            if (!empty($user['is_svip_one'])) {
                $read = Db::name('user_level')->where('id', 2)->value('read');
                $nums += $read;
            }
            if (!empty($user['is_svip_two'])) {
                $read = Db::name('user_level')->where('id', 4)->value('read');
                $nums += $read;
            }
        } else {
            if (empty($user['is_svip_one']) && empty($user['is_svip_two'])) {
                if (empty($user['is_vip_one']) && empty($user['is_vip_two'])) {
                    return error('请先开通vip');
                }
            }
            if (!empty($user['is_vip_one'])) {
                $read = Db::name('user_level')->where('id', 1)->value('read');
                $nums += $read;
            }
            if (!empty($user['is_vip_two'])) {
                $read = Db::name('user_level')->where('id', 3)->value('read');
                $nums += $read;
            }
            if (!empty($user['is_svip_one'])) {
                $read = Db::name('user_level')->where('id', 2)->value('read');
                $nums += $read;
            }
            if (!empty($user['is_svip_two'])) {
                $read = Db::name('user_level')->where('id', 4)->value('read');
                $nums += $read;
            }
        }
        //今日查看次数
        $start = strtotime(date('Y-m-d'));
        $end   = strtotime(date('Y-m-d 23:59:59'));
        $count = Db::name('news_sel')->where([['create_time', 'between', [$start, $end]], ['uid', '=', JWT_UID]])->count();
        if ($count >= $nums) {
            return error('今日可查看次数不足');
        }
        //如果已经加入公海，将is_read设置为1，方便后面导出只看过的数据
        $hai = Db::name('hai')->where(['news_id' => $param['id'], 'uid' => JWT_UID, 'type' => 1, 'is_read' => 0])->find();
        if (!empty($hai)) {
            Db::name('hai')->where('id', $hai['id'])->update(['is_read' => 1]);
        }
        $is_read = Db::name('news_sel')->where(['uid' => JWT_UID, 'news_id' => $param['id']])->find();
        if (empty($is_read)) {
            Db::name('news_sel')->insert([
                                             'uid'          => JWT_UID,
                                             'news_id'      => $param['id'],
                                             'news_file_id' => $news['news_file_id'],
                                             'create_time'  => time()
                                         ]);
        }
        return success('查看成功');
    }

    /**
     * svip定制线索列表
     */
    public function svipNews()
    {
        $param = get_params();
        $token = request()->header('token');
        if (!empty($token)) {
            $checkResult = Index::checkToken($token);
            $res         = json_decode($checkResult->getContent(), true);
            if ($res['code'] == 1) {
                $uid = $res['data']['userid'];
            }
        }

        // 记录性能
        $timing      = [];
        $start_total = microtime(true);

        $conditions = [
            'delete_time'  => 0,
            'news_file_id' => $param['id']
        ];

        if (!empty($param['province_id'])) {
            $province               = Db::name('citys')->where('id', $param['province_id'])->value('name');
            $conditions['province'] = $province;
        }
        if (!empty($param['city_id'])) {
            $city               = Db::name('citys')->where('id', $param['city_id'])->value('name');
            $conditions['city'] = $city;
        }
        if (!empty($param['district_id'])) {
            $district               = Db::name('citys')->where('id', $param['district_id'])->value('name');
            $conditions['district'] = $district;
        }
        if (!empty($param['cate_one'])) {
            $conditions['cate_one'] = $param['cate_one'];
        }
        if (!empty($param['cate_two'])) {
            $conditions['cate_two'] = $param['cate_two'];
        }
        if (!empty($param['yingye_id'])) {
            $ying                    = explode('/', $param['yingye_id']);
            $conditions['status_in'] = $ying;
        }
        if (!empty($param['lianxi'])) {
            $conditions['lianxi'] = $param['lianxi'];
        }

        if (!empty($param['riqi_year'])) {
            $conditions['riqi_year'] = $param['riqi_year'];
        }

        if (!empty($param['zhuce'])) {
            $conditions['zhuce'] = $param['zhuce'];
        }

        if (!empty($param['leixing'])) {
            $conditions['leixing'] = $param['leixing'];
        }

        if (!empty($param['canbao'])) {
            $conditions['canbao'] = $param['canbao'];
        }

        // 处理其他条件
        foreach (['zhaopin', 'wangluo', 'yuming', 'shangbiao', 'zhuanli', 'zhaobiao', 'gongzhong'] as $field) {
            if (!empty($param[$field])) {
                $conditions[$field] = $param[$field];
            }
        }

        if (!empty($param['keys'])) {
            $conditions['keys'] = $param['keys'];
        }

        // 使用Elasticsearch服务查询
        try {
            $start_es  = microtime(true);
            $esService = new ElasticsearchService();
            $page      = !empty($param['page']) ? (int)$param['page'] : 1;
            $pageSize  = 50;

            $result           = $esService->searchNews($conditions, $page, $pageSize);
            $list             = $result['list'];
            $total            = $result['total'];
            $timing['ES查询耗时'] = round(microtime(true) - $start_es, 4) . 's';

            // 获取所有符合条件的ID，用于添加到user_dao表
            $start_ids        = microtime(true);
            $idsResult        = $esService->getAllIds($conditions);
            $ids              = $idsResult['ids'];
            $timing['ID获取耗时'] = round(microtime(true) - $start_ids, 4) . 's';
            $timing['ID获取数量'] = count($ids);
            $timing['实际匹配总数'] = $idsResult['total'];
        } catch (Exception $e) {
            // 发生异常时回退到MySQL
            $timing['ES错误'] = $e->getMessage();
            // 回退到MySQL查询
            $where   = [];
            $where[] = ["delete_time", "=", 0];
            $where[] = ["news_file_id", "=", $param['id']];

            // 其他条件转换...
            // (这里省略了MySQL查询的完整转换逻辑)

            $list = Db::name('news')
                      ->where($where)
                      ->order('id desc')
                      ->page($param['page'])
                      ->limit(50)
                      ->select()
                      ->toArray();

            $total = Db::name('news')->where($where)->count();
            $ids   = Db::name('news')->where($where)->order('id desc')->limit(10000)->column('id');
        }

        // 处理列表数据
        $start_process = microtime(true);
        if (!empty($list) && !empty($uid)) {
            foreach ($list as &$val) {
                $val['is_sel'] = 0;
                $news_sel      = Db::name('news_sel')->where(['uid' => $uid, 'news_id' => $val['id']])->find();
                if (!empty($news_sel)) {
                    $val['is_sel'] = 1;
                }
                if (empty($val['mobile_more'])) {
                    $val['mobile_more'] = '';
                }
                if (empty($val['mobile'])) {
                    $val['mobile'] = '';
                }
            }
        }
        $timing['数据处理耗时'] = round(microtime(true) - $start_process, 4) . 's';

        // 处理ID字符串
        if (!empty($ids)) {
            $ids = implode(',', $ids);
        } else {
            $ids = '';
        }

        if (!empty($uid) && !empty($ids)) {
            $start_dao = microtime(true);
            Db::name('user_dao')->where(['uid' => $uid])->delete();
            Db::name('user_dao')->insert(['uid' => $uid, 'content' => $ids]);
            $timing['DAO保存耗时'] = round(microtime(true) - $start_dao, 4) . 's';
        }

        $timing['总耗时'] = round(microtime(true) - $start_total, 4) . 's';

        $return = [
            // 'ids' => $ids,
            'total'  => $total,
            'list'   => $list,
            '_debug' => $timing // 仅在调试模式下显示
        ];
        return success('', $return);
    }

    /**
     * svip首页线索
     */
    public function svipNewsFile()
    {
        $param = get_params();
        $sql[] = ['delete_time', '=', 0];
        if (!empty($param['keys'])) {
            $sql[] = ['title', 'like', "%{$param['keys']}%"];
        }
        $data = Db::name('news_file')->where($sql)
                  ->order('sort asc')->page($param['page'])->limit(10)->select();
        return success('', $data);
    }

    /**
     * svip首页数据
     */
    public function svipIndex()
    {

        $config  = Db::name('config')->where('id', 10)->find();
        $conf    = unserialize($config['content']);
        $setting = Db::name('config')->where('id', 16)->find();
        $set     = unserialize($setting['content']);

        //累计多少条线索
        // $nums = Db::name('news')->alias('n')
        //     ->join('news_file f','n.news_file_id=f.id')
        //     ->where([['n.delete_time','=',0],['n.news_file_id','>',0]])
        //     ->count();
        $data = [
            'nums' => 6000000,
            'conf' => $conf,
            'set'  => $set['hot_keyword'],
        ];
        return success('获取成功', $data);
    }

    /**
     * 根据省市区获取线索
     */
    public function getRegionBubbles()
    {
        $param = get_params();
        if (empty($param['parent_num'])) {
            return success('', []);
        }
        $city = Db::name('citys')->where('id', $param['parent_num'])->find();
        $data = Db::name('citys')->field('id,name,citycode,lng,lat')
                  ->where(['pid' => $city['id']])->order('id asc')->select()->toArray();
        if (empty($data) || $city['level'] == 3) {
            return success('', []);
        }

        foreach ($data as &$val) {
            if ($city['level'] == 1) {
                $sql   = [];
                $sql[] = ['city', 'like', "%{$val['name']}%"];
                if (!empty($param['is_svip'])) {
                    $sql[] = ['news_file_id', '>', 0];
                } else {
                    $sql[] = ['news_file_id', '=', 0];
                }
                $sql[]       = ['delete_time', '=', 0];
                $val['nums'] = Db::name('news')
                                 ->where($sql)
                                 ->count();
            } else {
                $sql   = [];
                $sql[] = ['district', 'like', "%{$val['name']}%"];
                if (!empty($param['is_svip'])) {
                    $sql[] = ['news_file_id', '>', 0];
                } else {
                    $sql[] = ['news_file_id', '=', 0];
                }
                $sql[]       = ['delete_time', '=', 0];
                $val['nums'] = Db::name('news')
                                 ->where($sql)
                                 ->count();
            }
        }
        return success('', $data);
    }

    /**
     * 企业详情
     */
    public function newsDetail()
    {
        $param                 = get_params();
        $data                  = Db::name('news')->where('id', $param['id'])->find();
        $data['cate_one_name'] = '';
        $data['cate_two_name'] = '';
        if (!empty($data['cate_one'])) {
            $data['cate_one_name'] = Db::name('news_cate')->where('id', $data['cate_one'])->value('title');
        }
        if (!empty($data['cate_two'])) {
            $data['cate_two_name'] = Db::name('news_cate')->where('id', $data['cate_two'])->value('title');
        }
        $data['is_sel'] = 0;
        $token          = request()->header('token');
        if (!empty($token)) {
            $checkResult = Index::checkToken($token);
            $res         = json_decode($checkResult->getContent(), true);
            if ($res['code'] == 1) {
                $uid = $res['data']['userid'];
            }
        }
        if (!empty($uid)) {
            $news_sel = Db::name('news_sel')->where(['uid' => $uid, 'news_id' => $param['id']])->find();
            if (!empty($news_sel)) {
                $data['is_sel'] = 1;
            }
        }
        return success('', $data);
    }

    /**
     * 客服
     */
    public function kefu()
    {
        $setting = Db::name('config')->where('id', 12)->find();
        $set     = unserialize($setting['content']);
        return success('', $set);
    }

    /**
     * 释放数据
     */
    public function fang()
    {
        $param = get_params();
        Db::name('hai')->where(['uid' => JWT_UID, 'type' => 2, 'news_type' => $param['news_type']])->delete();

        // $deleteNums = Db::name('search_total')->where('uid',JWT_UID)->value('zhanTotal');
        // $haiTotal = Db::name('search_total')->where('uid',JWT_UID)->value('haiTotal');
        // Db::name('search_total')->where('uid', JWT_UID)->update(['haiTotal' => $haiTotal - $deleteNums]);
        return success('操作成功');
    }

    /**
     * 回收站列表
     */
    public function zhanList()
    {
        $param     = get_params();
        $realTotal = Db::name('hai')->where(['uid' => JWT_UID, 'type' => 2, 'news_type' => $param['news_type']])->count();
        $data      = Db::name('hai')->alias('h')
                       ->join('news n', 'h.news_id=n.id')
                       ->field('n.*,h.id,h.is_read,h.is_dao,h.news_id')
                       ->where(['uid' => JWT_UID, 'type' => 2, 'news_type' => $param['news_type']])
                       ->order('h.id desc')
                       ->page($param['page'])
                       ->limit(500)
                       ->select()->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $news_sel = Db::name('news_sel')->where(['uid' => JWT_UID, 'news_id' => $val['news_id']])->find();
                if (!empty($news_sel)) {
                    $val['is_sel'] = 1;
                } else {
                    $val['is_sel'] = 0;
                }
            }
        }
        //   $nums = Db::name('search_total')->where('uid',JWT_UID)->value('zhanTotal');
        $res = [
            'list'  => $data,
            'total' => $realTotal,
        ];
        return success('', $res);
    }

    /**
     * 公海列表
     */
    public function haiList()
    {
        $param = get_params();
        $sql[] = ['uid', '=', JWT_UID];
        // 回收站还是公海
        $sql[]     = ['type', '=', 1];
        $sql[]     = ['news_type', '=', $param['news_type']];
        $realTotal = Db::name('hai')->where($sql)->count();
        if (!empty($param['is_dao'])) {
            if ($param['is_dao'] == 1) {
                $sql[] = ['is_dao', '=', 1];
            } else {
                $sql[] = ['is_dao', '=', 0];
            }
        }
        if (!empty($param['is_read'])) {
            if ($param['is_read'] == 1) {
                $sql[] = ['is_read', '=', 1];
            } else {
                $sql[] = ['is_read', '=', 0];
            }
        }

        // 获取筛选条件下的总数
        $filteredTotal = Db::name('hai')->where($sql)->count();

        $data = Db::name('hai')->alias('h')
                  ->join('news n', 'h.news_id=n.id')
                  ->field('n.*,h.id,h.news_id,h.is_read,h.is_dao')
                  ->where($sql)
                  ->order('h.id asc')
                  ->page($param['page'])
                  ->limit(500)
                  ->select()
                  ->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $news_sel = Db::name('news_sel')->where(['uid' => JWT_UID, 'news_id' => $val['news_id']])->count();
                if (!empty($news_sel)) {
                    $val['is_sel'] = 1;
                } else {
                    $val['is_sel'] = 0;
                }
            }
        }
        $user = Db::name('user')->where('id', JWT_UID)->find();
        $nums = 0;
        $dao  = 0;
        if ($param['news_type'] == 1) {
            if (!empty($user['is_vip_one'])) {
                $user_level = Db::name('user_level')->where('id', 1)->find();
//                $nums += $user_level['read'];
                $dao += $user_level['dao'];
            }
            if (!empty($user['is_vip_two'])) {
                $user_level = Db::name('user_level')->where('id', 3)->find();
//                $nums += $user_level['read'];
                $dao += $user_level['dao'];
            }
        } else {
            if (!empty($user['is_svip_one'])) {
                $user_level = Db::name('user_level')->where('id', 2)->find();
//                $nums += $user_level['read'];
                $dao += $user_level['dao'];
            }
            if (!empty($user['is_svip_two'])) {
                $user_level = Db::name('user_level')->where('id', 4)->find();
//                $nums += $user_level['read'];
                $dao += $user_level['dao'];
            }
        }
        //日查看次数
        $start = strtotime(date('Y-m-d'));
        $end   = strtotime(date('Y-m-d 23:59:59'));
        // $count = Db::name('news_sel')->where([['create_time','between',[$start,$end]],['uid','=',JWT_UID]])->count();
        $count = Db::name('news_dao')->where([['create_time', 'between', [$start, $end]], ['uid', '=', JWT_UID]])->count();
        $count = $dao - $count;
        // $nums = Db::name('hai')->where(['uid'=>JWT_UID,'news_type'=>$param['news_type'],'type'=>1])->count();

        // $isUpdate = Db::name('search_total')->where('uid',JWT_UID)->value('isUpdate');

        //  $nums_fake = Db::name('search_total')->where('uid',JWT_UID)->value('haiTotal');
        $nums_fake = $realTotal;
        if ($param['is_dao'] == 0 && $param['is_read'] == 0) {
            if ($param['news_type'] == 1) {
                $nums = $nums_fake;
            } else {
                $nums = $filteredTotal;

            }
            // if($nums_fake>10000){
            //     $nums = $nums_fake;
            // }else{
            //     $nums = $realTotal;
            // }
        } else if ($param['is_dao'] == 1 && $param['is_read'] == 0) {
            $nums = $filteredTotal;
        } else if ($param['is_dao'] == 2 && $param['is_read'] == 0) {
            $nums = $nums_fake - ($realTotal - $filteredTotal); // ($realTotal-$filteredTotal)为导出的数量
        } else if ($param['is_dao'] == 0 && $param['is_read'] == 1) {
            $nums = $filteredTotal;
        } else if ($param['is_dao'] == 1 && $param['is_read'] == 1) {
            $nums = $filteredTotal;
        } else if ($param['is_dao'] == 2 && $param['is_read'] == 1) {
            $nums = $filteredTotal;
        } else if ($param['is_dao'] == 0 && $param['is_read'] == 2) {
            $nums = $nums_fake - ($realTotal - $filteredTotal);
        } else if ($param['is_dao'] == 1 && $param['is_read'] == 2) {
            $nums = $filteredTotal;
        } else if ($param['is_dao'] == 2 && $param['is_read'] == 2) {
            $nums = $nums_fake - ($realTotal - $filteredTotal);
        }

        // 记录nums，用于同步回收站数量
        $numsRecord = Db::name('search_total')->where('uid', JWT_UID)->find();
        if ($numsRecord) {
            // 如果存在则更新
            Db::name('search_total')->where('uid', JWT_UID)->update(['zhanRecord' => $nums]);
        } else {
            // 如果不存在则插入
            Db::name('search_total')->insert(['uid' => JWT_UID, 'zhanRecord' => $nums]);
        }
        if ($param['news_type'] == 1) {
            $hai_title = Db::name('user')->where('id', JWT_UID)->value('hai_titlevip');


        } else {

            $hai_title = Db::name('user')->where('id', JWT_UID)->value('hai_titlesvip');
        }
        $return = [
            'hai_title'   => $hai_title,
            'dao'         => $dao,
            'total'       => $nums, //已选择xxx条数据
            'total_today' => $count, //今日最多还能导出xxx条数据
            'list'        => $data,
        ];

        return success('', $return);
    }

    /**
     * 加入公海
     */
    public function addHai()
    {
        $ishoutai = 0;

        // 更新 search_total
        $haiTotal = Db::name('search_total')->where('uid', JWT_UID)->value('total');
        Db::name('search_total')->where('uid', JWT_UID)->update([
                                                                    'haiTotal' => $haiTotal
                                                                ]);
        set_time_limit(0);

        $user = Db::name('user')->where('id', JWT_UID)->find();
        if (empty($user['status'])) {
            return error('您的账号已被禁用，请联系客服');
        }

        $param = get_params();
        if (empty($param['hai_title'])) {
            return error('请输入公海标题');
        }

        Db::name('user')->where('id', JWT_UID)->update(['hai_titlevip' => $param['hai_title']]);

        $user_dao = Db::name('user_dao')->where('uid', JWT_UID)->find();
        if (empty($user_dao['content'])) {
            return error('请选择要加入公海的线索');
        }
        $zxid        = $user_dao['id'];
        $conditions  = json_decode($user_dao['content'], true);
        $esService   = new ElasticsearchService();
        $page        = 1;
        $limit       = 5000;
        $insertCount = 0;
        $ii          = 1;
        while (true) {

            if ($ii++ >= 3) {

                $response = success('加入公海成功', "加入公海成功");
                echo $response->getContent();
                fastcgi_finish_request();

            }
            $result = $esService->getAllIds($conditions, $page, $limit);
            $ids    = $result['ids'] ?? [];
            if (empty($ids)) break;

            // 查询 news 数据
            $newsMap = Db::name('news')
                         ->where([
                                     ['id', 'in', $ids],
                                     ['delete_time', '=', 0]
                                 ])
                         ->column('*', 'id');

            if (empty($newsMap)) {
                $page++;
                continue;
            }

            // 判断新闻类型（只看第一条）
            $firstNews = reset($newsMap);
            $news_type = empty($firstNews['news_file_id']) ? 1 : 2;

            if ($news_type === 1 && empty($user['is_vip_one']) && empty($user['is_vip_two'])) {
                return error('请先开通VIP会员');
            }
            if ($news_type === 2 && empty($user['is_svip_one']) && empty($user['is_svip_two'])) {
                return error('请先开通SVIP会员');
            }

            // 删除旧记录只在第一页时执行一次
            if ($page === 1) {
                Db::name('hai')->where([
                                           'uid'       => JWT_UID,
                                           'type'      => 1,
                                           'news_type' => $news_type
                                       ])->delete();
            }

            // 查询已存在记录
            $existHaiIds = Db::name('hai')
                             ->where([['uid', '=', JWT_UID], ['news_id', 'in', $ids]])
                             ->column('news_id');
            $existHaiIds = array_flip($existHaiIds);

            // 查询是否查看
            $readSelIds = Db::name('news_sel')
                            ->where([['uid', '=', JWT_UID], ['news_id', 'in', $ids]])
                            ->column('news_id');
            $readSelIds = array_flip($readSelIds);

            // 准备插入
            $add = [];
            foreach ($ids as $newsId) {
                if (!isset($newsMap[$newsId])) continue;
                if (isset($existHaiIds[$newsId])) continue;

                $add[] = [
                    'uid'         => JWT_UID,
                    'type'        => 1,
                    'news_type'   => $news_type,
                    'news_id'     => $newsId,
                    'is_read'     => isset($readSelIds[$newsId]) ? 1 : 0,
                    'create_time' => time()
                ];
            }

            if (!empty($add)) {
                $user_dao1 = Db::name('user_dao')->where('uid', JWT_UID)->find();
                if (empty($user_dao1['content'])) {
                    return error('该任务任务已被删除');
                }
                if ($zxid != $user_dao1['id']) return error('该任务任务已被删除');
                Db::name('hai')->insertAll($add);
                $insertCount += count($add);
            }

            // 如果这一页的数据少于 limit，说明最后一页，退出
            if (count($ids) < $limit) break;

            $page++;
        }


        if ($insertCount === 0) {
            return error('没有新线索被加入');
        }

        return success("共加入 {$insertCount} 条线索到公海");
    }


    /**
     * 单条线索加入公海
     */
    public function addOneHai()
    {
        // 验证登录
        $param = get_params();
        $user  = Db::name('user')->where('id', JWT_UID)->find();
        if (empty($user['status'])) {
            return error('您的账号已被禁用，请联系客服');
        }

        // 输入公海标题
        if (empty($param['hai_title'])) {
            return error('请输入公海标题');
        }

        // 验证是否提供线索ID
        if (empty($param['ids'])) {
            return error('请提供要加入公海的线索ID');
        }

        // 查询线索信息
        $news = Db::name('news')->where([['id', '=', $param['ids']], ['delete_time', '=', 0]])->find();
        if (empty($news)) {
            return error('未找到相关线索信息');
        }

        // 判断线索类型并验证会员资格
        if ($news['news_file_id'] == 0) {
            $news_type = 1; // 普通线索
            if (empty($user['is_vip_one']) && empty($user['is_vip_two'])) {
                return error('请先开通VIP会员');
            }
            Db::name('user')->where('id', JWT_UID)->update(['hai_titlevip' => $param['hai_title']]);

        } else {
            $news_type = 2; // 企业线索
            if (empty($user['is_svip_one']) && empty($user['is_svip_two'])) {
                return error('请先开通SVIP会员');
            }
            Db::name('user')->where('id', JWT_UID)->update(['hai_titlesvip' => $param['hai_title']]);

        }

        // 检查线索是否已在用户的公海或回收站中
        $hai = Db::name('hai')->where(['news_id' => $param['ids'], 'uid' => JWT_UID])->find();
        if (!empty($hai)) {
            // if ($hai['type'] == 1) {
            return error('该线索已在您的公海中或者回收站中');
            // } else if ($hai['type'] == 2) {
            //     // 如果在回收站，则移回公海
            //     Db::name('hai')->where('id', $hai['id'])->update([
            //         'type' => 1,
            //         'update_time' => time()
            //     ]);
            //     return success('已从回收站恢复到公海');
            // }
        }

        // 准备添加到公海
        $is_read = Db::name('news_sel')->where(['news_id' => $param['ids'], 'uid' => JWT_UID])->find();
        $data    = [
            'uid'         => JWT_UID,
            'type'        => 1,
            'news_type'   => $news_type,
            'news_id'     => $param['ids'],
            'is_read'     => !empty($is_read) ? 1 : 0,
            'is_dao'      => 0,
            'create_time' => time()
        ];

        $haiTotal = Db::name('hai')->where('uid', JWT_UID)->count();
        if ($haiTotal == 0) {
            Db::name('search_total')->where('uid', JWT_UID)->update(['haiTotal' => 1]);
        } else {
            $haiTotal = Db::name('search_total')->where('uid', JWT_UID)->value('haiTotal');
            Db::name('search_total')->where('uid', JWT_UID)->update(['haiTotal' => $haiTotal + 1]);
        }

        $result = Db::name('hai')->insert($data);
        if ($result) {

            return success('加入公海成功');
        } else {
            return error('加入失败');
        }
    }

    /**
     * 移入回收站
     */
    public function addZhan()
    {
        $param = get_params();
//        if (empty($param['ids'])) {
//            return error('请选择要移入的线索');
//        }
//        Db::name('hai')->where([['id','in',$param['ids']]])->update(['type'=>2,'update_time'=>time()]);

        // if ($param['news_type'] == 1) {
        //     Db::name('hai')
        //         ->where(['uid'=>JWT_UID,'type'=>1,'news_type'=>1])
        //         ->order('id desc')
        //         ->limit(10000)
        //         ->update(['type'=>2,'update_time'=>time()]);
        // } else {
        //     Db::name('hai')
        //         ->where(['uid'=>JWT_UID,'type'=>1,'news_type'=>2])
        //         ->order('id desc')
        //         ->limit(10000)
        //         ->update(['type'=>2,'update_time'=>time()]);
        // }

        // 伪造
        // $zhanTotal = Db::name('search_total')->where('uid', JWT_UID)->value('haiTotal');
        // Db::name('search_total')->where('uid', JWT_UID)->update(['zhanTotal' => $zhanTotal]);

        // 构建查询条件
        $where = ['uid' => JWT_UID, 'type' => 1, 'news_type' => $param['news_type']];

        // 根据筛选条件添加查询条件
        // if (isset($param['is_dao'])) {
        //     $where['is_dao'] = intval($param['is_dao']);
        // }

        // if (isset($param['is_read'])) {
        //     $where['is_read'] = intval($param['is_read']);
        // }

        if (!empty($param['is_dao'])) {
            if ($param['is_dao'] == 1) {
                $where[] = ['is_dao', '=', 1];
            } else {
                $where[] = ['is_dao', '=', 0];
            }
        }
        if (!empty($param['is_read'])) {
            if ($param['is_read'] == 1) {
                $where[] = ['is_read', '=', 1];
            } else {
                $where[] = ['is_read', '=', 0];
            }
        }

        // 更新符合条件的数据
        $affected = Db::name('hai')
                      ->where($where)
            // ->order('id desc')
            // ->limit(10000)
                      ->update(['type' => 2, 'update_time' => time()]);

        // 伪造
        $zhanTotal = Db::name('search_total')->where('uid', JWT_UID)->value('zhanRecord');
        Db::name('search_total')->where('uid', JWT_UID)->update(['zhanTotal' => $zhanTotal]);
        $deleteNums = Db::name('search_total')->where('uid', JWT_UID)->value('zhanTotal');
        $haiTotal   = Db::name('search_total')->where('uid', JWT_UID)->value('haiTotal');
        Db::name('search_total')->where('uid', JWT_UID)->update(['haiTotal' => $haiTotal - $deleteNums]);

        return success('操作成功');
    }

    /**
     * 获取企业信息列表
     */
    public function news()
    {
        $param      = get_params();
        $conditions = [
            'delete_time'  => 0,
            'news_file_id' => 0
        ];
        // 记录性能
        $timing      = [];
        $start_total = microtime(true);

        if (!empty($param['province_id'])) {
            $province               = Db::name('citys')->where('id', $param['province_id'])->value('name');
            $conditions['province'] = $province;
        }
        if (!empty($param['city_id'])) {
            $city               = Db::name('citys')->where('id', $param['city_id'])->value('name');
            $conditions['city'] = $city;
        }
        if (!empty($param['district_id'])) {
            $district               = Db::name('citys')->where('id', $param['district_id'])->value('name');
            $conditions['district'] = $district;
        }
        if (!empty($param['cate_one'])) {
            $conditions['cate_one'] = $param['cate_one'];
        }
        if (!empty($param['cate_two'])) {
            $conditions['cate_two'] = $param['cate_two'];
        }
        if (!empty($param['yingye_id'])) {
            $ying                    = explode('/', $param['yingye_id']);
            $conditions['status_in'] = $ying;
        }
        if (!empty($param['lianxi'])) {
            $conditions['lianxi'] = $param['lianxi'];
        }
        if (!empty($param['riqi_year'])) {
            $conditions['riqi_year'] = $param['riqi_year'];
        }
        if (!empty($param['zhuce'])) {
            $conditions['zhuce'] = $param['zhuce'];
        }
        if (!empty($param['leixing'])) {
            $conditions['leixing'] = $param['leixing'];
        }
        if (!empty($param['canbao'])) {
            $conditions['canbao'] = $param['canbao'];
        }

        // 处理其他条件
        foreach (['zhaopin', 'wangluo', 'yuming', 'shangbiao', 'zhuanli', 'zhaobiao', 'gongzhong'] as $field) {
            if (!empty($param[$field])) {
                $conditions[$field] = $param[$field];
            }
        }

        if (!empty($param['keys'])) {
            $conditions['keys'] = $param['keys'];
        }

        // 使用Elasticsearch服务查询
        $start_es = microtime(true);

        $page         = !empty($param['page']) ? (int)$param['page'] : 1;
        $pageSize     = 10000;
        $isBasicQuery = (count($conditions) == 2);
        if ($isBasicQuery) {
            // 基础查询 + 第1页，尝试使用缓存
            // $result = Cache::remember('es_news_list_page500', function () use ($esService, $conditions, $page, $pageSize) {
            //     return $esService->searchNews($conditions, $page, $pageSize);
            // }, 180000);
            $offset = ($page - 1) * $pageSize;
            $token = request()->header('token');
            $uid   = 0;
            if (!empty($token)) {
                $checkResult = Index::checkToken($token);
                $res         = json_decode($checkResult->getContent(), true);
                if ($res['code'] == 1) {
                    $uid = $res['data']['userid'];
                }
            }
            if ($uid > 0) {
                $list = Db::name('news')
                          ->alias('n')
                          ->leftJoin('news_sel ns', "n.id = ns.news_id AND ns.uid = $uid")
                          ->where('n.delete_time', 0)
                          ->where('n.news_file_id', 0)
                          ->order('n.has_mobile', 'desc')
                          ->order('n.is_status_active', 'desc')
                          ->order('n.riqi', 'desc')
                          ->limit($offset, $pageSize)
                          ->field('n.*, IF(ns.news_id IS NOT NULL, 1, 0) as is_sel')
                          ->select();
            } else {
                $list = Db::name('news')
                          ->where("delete_time", 0)
                          ->where("news_file_id", 0)
                          ->order('has_mobile', 'desc')
                          ->order('is_status_active', 'desc')
                          ->order('riqi', 'desc')
                          ->limit($offset, $pageSize)
                          ->select();
            }


            $total = Db::name('news')->order('id desc')->count();// Db::name('news_total')->where('id',1)->value('total');


            $return = [
                'total' => $total,
                'list'  => $list,
                'param' => $param,
                'token' => $token
            ];
            return success('', $return);
        } else {
            $esService        = new ElasticsearchService();
            $result           = $esService->searchNews($conditions, $page, $pageSize);
            $total            = $result['total'];
            $timing['ES缓存']   = '缓存查询';
            $timing['ES查询耗时'] = round(microtime(true) - $start_es, 4) . 's';
            $list = $result['list'];
            // 判断是否为简单查询，如果是则使用预设的总数
            //
            // if ($isBasicQuery) {

            //   //  $total = Db::name('news_total')->where('id',1)->value('total');
            // } else {

            // 获取所有符合条件的ID，用于添加到user_dao表

            // $timing['实际匹配总数'] = $idsResult['total'];
            // }
            // catch (\Exception $e) {
            //     // 发生异常时回退到MySQL
            //     $timing['ES错误'] = $e->getMessage();
            //     // 回退到MySQL查询
            //     $where = [];
            //     $where[] = ["delete_time","=",0];
            //     $where[] = ["news_file_id","=",0];
            //     if (!empty($param['province_id'])) {
            //         $province = Db::name('citys')->where('id',$param['province_id'])->value('name');
            //         $where[] = ['province','=',$province];
            //     }
            //     // 其他条件转换...
            //     // (这里省略了MySQL查询的完整转换逻辑)
            //     $list = Db::name('news')
            //         ->field('id,name,status,riqi,faren,province,city,district,address,daima')
            //         ->where($where)
            //         ->order('id desc')
            //         ->page($param['page'])
            //         ->limit(20)
            //         ->select()
            //         ->toArray();
            //     if (count($where) == 2) {
            //         $total = Db::name('news_total')->where('id',1)->value('total');
            //     } else {
            //         $total = Db::name('news')->where($where)->count();
            //         $ids = Db::name('news')->where($where)->order('id desc')->limit(10000)->column('id');
            //     }
            // }

            $uid = 1;

            $token = request()->header('token');
            if (!empty($token)) {
                $checkResult = Index::checkToken($token);
                $res         = json_decode($checkResult->getContent(), true);
                if ($res['code'] == 1) {
                    $uid = $res['data']['userid'];
                }
            }
            $start_dealsj = microtime(true);


            // 处理列表数据
            if (!empty($list)) {
                foreach ($list as &$val) {
                    $val['is_sel'] = 0;
                    if (!empty($uid)) {
                        $news_sel = Db::name('news_sel')->where(['uid' => $uid, 'news_id' => $val['id']])->find(); // 查询用户是否查看过该线索
                        if (!empty($news_sel)) {
                            $val['is_sel'] = 1;
                        }
                    }
                    if (empty($val['mobile_more'])) {
                        $val['mobile_more'] = '';
                    }
                    if (empty($val['mobile'])) {
                        $val['mobile'] = '';
                    }
                }
                // 注意：引用结束后，必须手动释放引用
                unset($val);
            }
            $timing['处理列表数据'] = round(microtime(true) - $start_dealsj, 4) . 's';

            // 检查search_total表中是否存在该用户的记录
            $searchTotal = Db::name('search_total')->where('uid', $uid)->find();
            if ($searchTotal) {
                // 如果存在则更新
                Db::name('search_total')->where('uid', $uid)->update(['total' => $total]);
            } else {
                // 如果不存在则插入
                Db::name('search_total')->insert(['uid' => $uid, 'total' => $total]);
            }
            // 只是搜索的话（不加入公海），将isUpdate字段归0
            // Db::name('search_total')->where('uid', $uid)->update(['isUpdate' => 0]);


            $return = [
                //  'ids' => $ids,
                'total'  => $total,
                'list'   => $list,
                '_debug' => $timing, // 仅在调试模式下显示
                'param'  => $param,
                'token'  => $token
            ];
            Db::name('user_dao')->where(['uid' => $uid])->delete();
            Db::name('user_dao')->insert(['uid' => $uid, 'content' => json_encode($conditions)]);

            $timing['总耗时'] = round(microtime(true) - $start_total, 4) . 's';
            return success('', $return);

//         header('Content-Type: application/json');
// $response = success('', $return);
// echo $response->getContent(); // 获取字符串内容并输出


            //  fastcgi_finish_request();

            //         $start_ids = microtime(true);
            //         $idsResult = $esService->getAllIds($conditions);
            //       //  var_dump($idsResult);
            //       $ids = $idsResult['ids'];
            //   //  $ids=[];
            //         $timing['ID获取耗时'] = round(microtime(true) - $start_ids, 4) . 's';
            //         $timing['ID获取数量'] = count($ids);
            //     // 处理ID字符串
            //     if (!empty($ids)) {
            //         $ids = implode(',', $ids);
            //     } else {
            //         $ids = '';
            //     }

            //     if (!empty($uid) && !empty($ids)) {
            //         Db::name('user_dao')->where(['uid'=>$uid])->delete();
            //         Db::name('user_dao')->insert(['uid'=>$uid,'content'=>$ids]);
            //     }
        }
    }


    //城市列表
    public function cityList()
    {
        $province = Db::name('citys')->field('id,name,pid,lng,lat')->where(['level' => 1])->order('id asc')->select()->toArray();
        foreach ($province as &$val) {
            $val['value'] = $val['id'];
            $val['label'] = $val['name'];
            $city         = Db::name('citys')->field('id,name,pid,lng,lat')->where(['level' => 2, 'pid' => $val['id']])
                              ->order('id asc')->select()->toArray();
            foreach ($city as &$v) {
                $v['value'] = $v['id'];
                $v['label'] = $v['name'];
                $dis        = Db::name('citys')->field('id,name,pid,lng,lat')->where(['level' => 3, 'pid' => $v['id']])
                                ->order('id asc')->select()->toArray();
                foreach ($dis as &$vv) {
                    $vv['value'] = $vv['id'];
                    $vv['label'] = $vv['name'];
                }
                $v['children'] = $dis;
            }
            $val['children'] = $city;
        }
        return success('', $province);
    }

    /**
     * 首页数据
     */
    public function index()
    {
        $config  = Db::name('config')->where('id', 10)->find();
        $conf    = unserialize($config['content']);
        $setting = Db::name('config')->where('id', 16)->find();
        $set     = unserialize($setting['content']);
        //累计多少条线索
        $nums = Db::name('news_total')->where('id', 1)->value('total');
        //系统通知
        $notice = Db::name('notice')->field('id,content')
                    ->where([['delete_time', '=', 0]])
                    ->order('id desc')
                    ->select();
        $data   = [
            'notice' => $notice,
            'nums'   => $nums,
            'conf'   => $conf,
            'set'    => $set['hot_keyword'],
        ];
        return success('获取成功', $data);
    }

    /**
     * 筛选信息
     */
    public function shai()
    {
        //所属行业
        $hangye = Db::name('news_cate')->field('id,title')
                    ->where([['delete_time', '=', 0], ['pid', '=', 0]])->order('sort asc')->select()->toArray();
        if (!empty($hangye)) {
            $erji = [['id' => 0, 'title' => '不限']];
            foreach ($hangye as &$v) {
                $child      = Db::name('news_cate')->field('id,title')
                                ->where([['delete_time', '=', 0], ['pid', '=', $v['id']]])->order('sort asc')->select()->toArray();
                $v['child'] = array_merge($erji, $child);
            }
        }
        $hy             = [['id' => 0, 'title' => '不限', 'child' => ['id' => 0, 'title' => '不限']]];
        $data['hangye'] = array_merge($hy, $hangye);
        //营业状态
        $data['yingye'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '在营/存续', 'value' => '在营/存续'],
            ['id' => 2, 'title' => '迁入/迁出', 'value' => '迁入/迁出'],
            ['id' => 3, 'title' => '吊销/撤销', 'value' => '吊销/撤销'],
            ['id' => 4, 'title' => '注销', 'value' => '注销'],
            ['id' => 5, 'title' => '停业', 'value' => '停业'],
            ['id' => 6, 'title' => '其他', 'value' => '其他'],
        ];
        //联系方式
        $data['lianxi'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有手机', 'value' => '有手机'],
            ['id' => 2, 'title' => '有固话', 'value' => '有固话'],
            ['id' => 3, 'title' => '有邮箱', 'value' => '有邮箱'],
            ['id' => 4, 'title' => '有QQ', 'value' => '有QQ'],
            ['id' => 5, 'title' => '无联系方式', 'value' => '无联系方式'],
        ];
        //成立年限
        $data['chengli'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '1年以内', 'value' => '1年以内'],
            ['id' => 2, 'title' => '1-5年', 'value' => '1-5'],
            ['id' => 3, 'title' => '5-10年', 'value' => '5-10'],
            ['id' => 4, 'title' => '10-15年', 'value' => '10-15'],
            ['id' => 5, 'title' => '15年以上', 'value' => '15年以上'],
        ];
        //注册资金
        $data['zhuce'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '20万以下', 'value' => '20万以下'],
            ['id' => 2, 'title' => '20~50万', 'value' => '20~50'],
            ['id' => 3, 'title' => '50~100万', 'value' => '50~100'],
            ['id' => 4, 'title' => '100~200万', 'value' => '100~200'],
            ['id' => 5, 'title' => '200~500万', 'value' => '200~500'],
            ['id' => 6, 'title' => '500万以上', 'value' => '500万以上'],
        ];
        //企业类型
        $qiCate = Db::name('qi_cate')->field('id,title')->where(['delete_time' => 0])->order('id desc')->select()->toArray();

        if (!empty($qiCate)) {
            foreach ($qiCate as &$v) {
                $v['value'] = $v['title'];
            }
        }
        $leixing = [['id' => 0, 'title' => '不限', 'value' => '']];

        $data['leixing'] = array_merge($leixing, $qiCate);
        //参保人数
        $data['canbao'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '小于20人', 'value' => '小于20人'],
            ['id' => 2, 'title' => '10~15人', 'value' => '10~15'],
        ];
        //招聘情况
        $data['zhaopin'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有招聘情况', 'value' => '有招聘情况'],
            ['id' => 2, 'title' => '无招聘情况', 'value' => '无招聘情况'],
        ];
        //网站推广
        $data['wangluo'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有网络推广', 'value' => '有网络推广'],
            ['id' => 2, 'title' => '无网络推广', 'value' => '无网络推广'],
        ];
        //网站域名
        $data['yuming'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有域名', 'value' => '有域名'],
            ['id' => 2, 'title' => '无域名', 'value' => '无域名'],
        ];
        //商标
        $data['shangbiao'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有商标', 'value' => '有商标'],
            ['id' => 2, 'title' => '无商标', 'value' => '无商标'],
        ];
        //专利
        $data['zhuanli'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有专利', 'value' => '有专利'],
            ['id' => 2, 'title' => '无专利', 'value' => '无专利'],
        ];
        //招投标
        $data['zhaobiao'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有招投标', 'value' => '有招投标'],
            ['id' => 2, 'title' => '无招投标', 'value' => '无招投标'],
        ];
        //专利
        $data['gongzhong'] = [
            ['id' => 0, 'title' => '不限', 'value' => ''],
            ['id' => 1, 'title' => '有公众号', 'value' => '有公众号'],
            ['id' => 2, 'title' => '无公众号', 'value' => '无公众号'],
        ];
        return success('', $data);
    }

    /**
     * 立即购买
     */
    public function toPay()
    {
        $param    = get_params();
        $device   = Db::name('device')->alias('d')
                      ->join('cate c', 'd.cate_id=c.id')
                      ->field('d.*,c.title as cate_name')
                      ->where('d.id', $param['device_id'])
                      ->find();
        $recharge = Db::name('recharge')->field('id,nums,amount,score,desc')
                      ->where('id', $param['recharge_id'])->find();
        if ($recharge['nums'] > $device['weight']) {
            return error('当前设备剩余酒量不足');
        }
        $shop   = Db::name('user_one')->field('id,user_name,mobile,address')
                    ->where('id', $device['user_one'])->find();
        $user   = Db::name('user')->where('id', JWT_UID)->find();
        $insert = [
            'uid'           => JWT_UID,
            'device_id'     => $param['device_id'],
            'recharge_info' => json_encode($recharge, JSON_UNESCAPED_UNICODE),
            'wine_num'      => $recharge['nums'],
            'wine_name'     => $device['cate_name'],
            'order_no'      => date('YmdHis') . rand(1000, 9999),
            'out_found_no'  => 'BK' . date('YmdHis') . rand(100, 999),
            'address'       => json_encode($shop, JSON_UNESCAPED_UNICODE),
            'pay_type'      => $param['pay_type'],
            'create_time'   => time(),
        ];
        $work   = new Work();
        //服务器下发订单预创建信息
        $topic = 'liquor/s/' . $device['imei'] . '/order';
//        $msg = json_encode([
//            "msgId" => $device['msgId'],
//            "type"  => "pre_create"
//        ]);
//        $work->preOrder($topic,$msg);
        //服务器下发订单创建信息
        $msg = json_encode([
                               "orderNum" => $insert['order_no'],
                               "weight"   => $insert['wine_num'],
                               "msgId"    => $device['msgId'],
                               "type"     => "create"
                           ]);
        $work->preOrder($topic, $msg);
        switch ($insert['pay_type']) {
            case 1:
                //微信支付
                $insert['amount'] = $recharge['amount'];
                $orderId          = Db::name('order')->insertGetId($insert);
                $notify_url       = request()->domain() . "/api/notify/payResult";
                $wx               = new WxPay();
                $res              = $wx->pay($insert['order_no'], $user['openid'], $notify_url, $insert['amount']);
                if (!empty($res['code'])) {
                    //支付失败
                    return json($res);
                }
                $res['data']['order_id'] = $orderId;
                return json($res);
                break;
            case 2:
                //积分支付
                $insert['amount'] = $recharge['score'];
                if ($user['score'] < $insert['amount']) {
                    return error('积分不足');
                }
                $insert['status']     = 1;
                $insert['pay_status'] = 1;
                $insert['pay_time']   = time();
                $orderId              = Db::name('order')->insertGetId($insert);
                Db::name('user')->where('id', $insert['uid'])->dec('score', $insert['amount'])->update();
                //服务器下发订单支付成功信息
                $msg = json_encode([
                                       "orderNum" => $insert['order_no'],
                                       "weight"   => $insert['wine_num'],
                                       "msgId"    => $device['msgId'],
                                       "type"     => "pay"
                                   ]);
                $work->preOrder($topic, $msg);
                //积分消费记录
                Db::name('score_log')->insert([
                                                  'uid'         => $insert['uid'],
                                                  'title'       => '兑换酒量',
                                                  'type'        => 2,
                                                  'num'         => $insert['amount'],
                                                  'create_time' => time(),
                                              ]);
                return json(['code' => 0, 'msg' => '支付成功', 'data' => ['order_id' => $orderId]]);
                break;
        }
    }

    /**
     * 支付成功页
     */
    public function successResult()
    {
        $param                 = get_params();
        $data                  = Db::name('order')->alias('o')
                                   ->join('device d', 'o.device_id=d.id')
                                   ->join('cate c', 'd.cate_id=c.id')
                                   ->field('o.*,d.device_name,d.imei,c.title as cate_name')
                                   ->where('o.id', $param['id'])
                                   ->find();
        $data['wine_num_text'] = $data['wine_num'] . 'ML';
        $data['create_time']   = datetime($data['create_time']);
        $data['pay_time']      = datetime($data['pay_time']);
        return success('', $data);
    }


    /**
     * 附近售酒机
     */
    public function deviceList()
    {
        $param = get_params();
        $addr  = '';
        if (!empty($param['lng']) && !empty($param['lat'])) {
            //根据经纬度获取当前位置
            $address = getGeolocationFromCoordinates($param['lat'], $param['lng']);
            $json    = json_decode($address, true);
            $addr    = $json['msg'];
        }
        $page = 1;
        if (!empty($param['page'])) {
            $page = $param['page'];
        }
        $sql[] = ['d.status', '=', 'run'];
        $sql[] = ['d.delete_time', '=', 0];
        if (!empty($param['cate_id'])) {
            $sql[] = ['d.cate_id', '=', $param['cate_id']];
        }
        $deviceList = Db::name('device')->alias('d')
                        ->join('user_one u', 'd.user_one=u.id')
                        ->join('cate c', 'd.cate_id=c.id')
                        ->field('d.*,u.mobile,u.address,u.lng,u.lat,c.title as wine_name')
                        ->where($sql)
                        ->order('d.id desc')
                        ->select()
                        ->toArray();
        if (!empty($deviceList)) {
            $config = Db::name('config')->where('id', 10)->find();
            $conf   = unserialize($config['content']);
            foreach ($deviceList as &$val) {
                if (!empty($val['lng']) && !empty($val['lat']) && !empty($param['lat']) && !empty($param['lng'])) {
                    $val['distance'] = distanceBetween($val['lat'], $val['lng'], $param['lat'], $param['lng']);
                } else {
                    $val['distance'] = 0;
                }
                $val['device_img'] = $conf['device_img'];
            }
            $distance = array_column($deviceList, 'distance');
            array_multisort($distance, SORT_ASC, $deviceList);
            $pageSize   = 10;
            $pages      = ($page - 1) * $pageSize;
            $deviceList = array_splice($deviceList, $pages, $pageSize);
        }
        $return = [
            'address' => $addr,
            'list'    => $deviceList,
        ];
        return success('', $return);
    }

    /**
     * 图片上传
     */
    public function uploadImg()
    {
        if (request()->isPost()) {
            // 错误提示语
            $error = "";
            // 上传图片
            $result = upload_image('file', '', $error);
            if (!$result) {
                return json(['code' => 1, 'msg' => '上传失败', 'data' => $error]);
            }
            // 多图片上传处理
            $list = [];
            if (is_array($result)) {
                foreach ($result as $val) {
                    $list[] = $val;
                }
            } else {
                $list = $result;
            }
            return json(['code' => 0, 'msg' => '上传成功', 'data' => $list]);
        }
    }

    /**
     * 视频上传
     */
    public function uploadVideo()
    {
        $result = upload_file('file', '', $error);
        if (!$result) {
            return json(['code' => 1, 'msg' => '上传失败', 'data' => $error]);
        }
        // 上传处理
        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $list[] = $val;
            }
        } else {
            $list = $result;
        }
        if (!empty($list[0])) {
            $url = $list[0];
        } else {
            $url = '';
        }
        return json(['code' => 0, 'msg' => '上传成功', 'data' => $url, 'path' => get_image_url($url)]);
    }
}